<template>
  <ListPage ref="page" :columns="columns" :query="query" :api="getCustomerConsultationRecord">
    <template #search="{ page, sort, columns, hiddenColumns }">
      <PageSearch ref="search" :query="query" :page="page" :columns="columns" has-box
        @search="() => ($refs.page as any).getData()">
        <template #auth>
          <ElButton v-if="auth.has('add')" type="primary" @click="onAddCustomer">添加新客户</ElButton>
          <ElButton v-if="auth.has('export')" @click="onExportData(sort)">导出数据</ElButton>
          <ElButton v-if="auth.has('batchedit')" @click="storeLiaisonDialogTableVisible = true">批量修改对接人</ElButton>
        </template>
        <template #input="{ isCollapse, showTrigger }">
          <SearchInput v-model="query.keyword" placeholder="客户名称/客户ID/店铺ID/店铺名称" :isCollapse="isCollapse"
            :showTrigger="showTrigger" :data="query" :columns="columns" :hidden-columns="(hiddenColumns as any)"
            @trigger="(e) => ($refs.search as any).trigger(e)" @search="() => ($refs.page as any).getData()"
            @change-column="(prop) => ($refs.page as any).changeColumn(prop)"></SearchInput>
        </template>
        <ElFormItem label="客户ID">
          <ElInput v-model="query.customerNo"></ElInput>
        </ElFormItem>
        <ElFormItem label="客户名称">
          <ElInput v-model="query.customerName"></ElInput>
        </ElFormItem>
        <ElFormItem label="店铺ID">
          <ElInput v-model="query.shopNo"></ElInput>
        </ElFormItem>
        <ElFormItem label="店铺名称">
          <ElInput v-model="query.shopName"></ElInput>
        </ElFormItem>
        <ElFormItem label="店铺类别">
          <ElInput v-model="query.shopTypeNo"></ElInput>
        </ElFormItem>
        <ElFormItem label="店铺对接人">
          <ElInput v-model="query.storeLiaison"></ElInput>
        </ElFormItem>
        <ElFormItem label="首次服务">
          <!-- firstStartDateEnd
          <ElInput v-model="query.firstStartDateStart"></ElInput> -->
          <ElDatePicker v-model="firstStartDate" format="YYYY-MM-DD" valueFormat="YYYY-MM-DD" type="daterange"
            clearable />
        </ElFormItem>
        <ElFormItem label="收费模式">
          <ElSelect v-model="query.feeModel">
            <ElOption label="合并收费" value="0" />
            <ElOption label="单独收费" value="1" />
          </ElSelect>
        </ElFormItem>
        <ElFormItem label="剔除退款">
          <ElSelect v-model="query.excludingRefunds">
            <ElOption label="是" value="1" />
            <ElOption label="否" value="0" />
          </ElSelect>
        </ElFormItem>
        <!-- <ElFormItem label="客服类型">
           <ApiSelect v-model="query.customTypeNo" :api="getAllCustomType" value-key="val" label-key="name" />
        </ElFormItem> -->
        <ElFormItem label="到期提醒天数">
          <ElSelect v-model="query.stopDays">
            <ElOption label="已过期" value="-1" />
            <ElOption label="1天" value="1" />
            <ElOption label="3天" value="3" />
            <ElOption label="7天" value="7" />
            <ElOption label="15天" value="15" />
            <ElOption label="30天" value="30" />
          </ElSelect>
        </ElFormItem>
        <ElFormItem>
          <DictSelect :query="query as any" />
        </ElFormItem>
      </PageSearch>

      <StoreLiaison v-model="storeLiaisonDialogTableVisible"></StoreLiaison>
    </template>

    <template #table="{ data, hiddenColumns }">
      <ListTable :data="data" :hidden-columns="(hiddenColumns as any)" @sort-change="onSortChange"
        @edit-custom="onEditCustom" @add-shop="onAddShop" @edit-shop="onEditShop" @stop-cooperation="onStopCooperation"
        @show-custom-detail="onShowCustomDetail" @go-shop="onGoShop" @copy2="onCopy" @stop-notice="onStopNotice"
        @change-log="onChangeLog" @delete-custom="onDeleteCustom" @add-sub-account="onAddSubAccount"
        @show-customer-level="onShowCustomerLevel" @view-sub="onViewSub"></ListTable>
    </template>

    <template #pagination="{ page, total }">
      <PagePagination :page="page" :total="total" @changePage="(v) => ($refs.page as any).changePage(v)">
      </PagePagination>
      <CustomerLeveDetail ref="customerLeveDetailRef" />
    </template>

    <template #drawer="{ row }">
      <DrawerDetail :row="row" @edit-shop="onEditShop" @stop-cooperation="onStopCooperation" @stop-notice="onStopNotice"
        @copy="onCopy" @change-log="onChangeLog" />
    </template>
  </ListPage>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import { ElMessage, ElMessageBox, ElOption, ElSelect } from 'element-plus'
import { useRoute } from 'vue-router'
import ListPage from '@/components/list-page/ListPage.vue'
import PageSearch from '@/components/list-page/PageSearch.vue'
import PagePagination from '@/components/list-page/PagePagination.vue'
import SearchInput from '@/components/list-page/SearchInput.vue'
import ListTable from './ListTable.vue'
import DrawerDetail from './DrawerDetail.vue'
import { addDialog, editDialog } from '../dialog/customerDialog'
import { addShopInCustomDialog, editShopDialog } from '../dialog/shopDialog'
import { stopDialog } from '../dialog/stopCooperationDialog'
import { changeLogDialog } from '../dialog/changeLogDialog'
import { subDialog } from '../dialog/subDialog'
import { copyToClipboard } from '@/utils/common'
import { getCustomerConsultationRecord, customerShopNotice, removeCustomerConsultationRecord, getAllCustomType } from '../api'
import { exportExcel } from '@/utils/common'
import { useAuth } from '@/utils/auth'
import { addSubAccountDialog } from '../../sub-account-management/dialog'
// import ApiSelect from '@/components/form-item/ApiSelect.vue'
import StoreLiaison from "@/views/menus/customer-management/components/StoreLiaison.vue";
import CustomerLeveDetail from './CustomerLeveDetail.vue'
import DictSelect from './DictSelect.vue'

const route = useRoute()

const page = ref()

const auth = useAuth()

const storeLiaisonDialogTableVisible = ref(false)

const stopDaysDefault = sessionStorage.getItem('CustomerManagement.stopDays') || ''
sessionStorage.removeItem('CustomerManagement.stopDays')

const query = reactive({
  keyword: '',
  customerNo: '',
  customerName: '',
  shopNo: '',
  shopName: '',
  shopTypeNo: '',
  storeLiaison: '',
  firstStartDateStart: '',
  firstStartDateEnd: '',
  customTypeNo: '',
  stopDays: stopDaysDefault,
  feeModel: '',
  excludingRefunds: ''
})

const columns = computed(() => [
  { label: '客户等级', prop: 'customerLvl' },
  { label: '客户名称', prop: 'customerName' },
  { label: '营销类型', prop: 'marketTypeName' },
  { label: '拓客渠道', prop: 'expandTypeName' },
  { label: '平台', prop: 'platformName' },
  { label: '店铺名称', prop: 'shopName' },
  { label: '店铺类别', prop: 'shopTypeName' },
  { label: '店铺分组', prop: 'shopGroup' },
  { label: '首次服务日期', prop: 'firstStartDate' },
  { label: '开始日期', prop: 'startDate' },
  { label: '结束日期', prop: 'endDate' },
  { label: '客服类型', prop: 'customTypeName' },
  { label: '收费模式', prop: 'feeModel' },
  { label: '底薪（元）', prop: 'baseSalary' },
  { label: '提成（%）', prop: 'commission' },
  { label: '店铺对接人', prop: 'storeLiaison' },
  { label: '剔除退款', prop: 'excludingRefunds' },
  { label: '录入人', prop: 'createUserName' }
])

const firstStartDate = computed({
  get() {
    return [query.firstStartDateStart, query.firstStartDateEnd]
  },
  set(v) {
    const val = v || []
    query.firstStartDateStart = val[0]
    query.firstStartDateEnd = val[1]
  }
})

const onAddCustomer = async () => {
  await addDialog.open()
  page.value && page.value.getData()
}

const onEditCustom = async (row) => {
  await editDialog.open({ row: { customerId: row.customerId, customerNo: row.customerNo, customerName: row.customerName } })
  page.value && page.value.getData()
}

const onAddShop = async row => {
  await addShopInCustomDialog.open({ row: { customerId: row.customerId } })
  page.value && page.value.getData()
}

const onEditShop = async row => {
  await editShopDialog.open({ row: { shopId: row.shopId } })
  page.value && page.value.getData()
  page.value && page.value.closeDrawer()
}

const onStopCooperation = async row => {
  if (row.feeModel === 0) {
    await ElMessageBox.confirm('当前店铺是合并店铺，是否确认继续修改？', '', {
      cancelButtonText: '暂不修改',
      confirmButtonText: '继续修改'
    })
    stopDialog.title('停止合作 该店铺合并收费，请确认收费标准是否需要调整？')
  } else {
    stopDialog.title('停止合作')
  }

  await stopDialog.open({ row: { shopId: row.shopId } })
  page.value && page.value.getData()
  page.value && page.value.closeDrawer()
  ElMessage({
    message: '操作成功！',
    type: 'success'
  })
}

const onShowCustomDetail = async row => {
  page.value && page.value.openDrawer(row)
}

const onGoShop = async row => {
  if (row.shopLinkUrl) {
    window.open(row.shopLinkUrl, '_blank')
  }
}

const onCopy = async row => {
  const text = `${row.shopName || ''}
店铺平台：${row.platformName || ''}
店铺类目：${row.shopTypeName || ''}
客户名称：${row.customerName || ''}
店铺名称：${row.shopName || ''}
服务日期：${row.startDate || ''}~${row.endDate || ''}
客服类型：${row.customTypeName || ''}
服务班次：${row.serviceShiftName || ''}
收费标准：${row.baseSalary || 0}元+${row.commission || 0}%
咨询数量：${row.consultPeopleNum || 0}人
对接平台：${row.dockingPlatform || ''}
特别备注：${row.customerServiceMessage || ''}`
  await copyToClipboard(text)
  ElMessage({
    message: '复制成功！',
    type: 'success'
  })
}

const onStopNotice = async row => {
  await customerShopNotice({ shopId: row.shopId })
  ElMessage({
    message: '操作成功！',
    type: 'success'
  })
}

const onChangeLog = async row => {
  changeLogDialog.open({ query: { shopId: row.shopId } })
}

const onExportData = async (sort) => {
  await exportExcel({ url: route.name, condition: query, sort })
}

const onDeleteCustom = async row => {
  await ElMessageBox.confirm('是否确定删除？', '提示')
  await removeCustomerConsultationRecord([row.customerId])
  page.value && page.value.getData()
  page.value && page.value.closeDrawer()
  ElMessage({
    message: '操作成功！',
    type: 'success'
  })
}

const onAddSubAccount = async row => {
  await addSubAccountDialog.open({ row: row })
  page.value && page.value.getData()
  page.value && page.value.closeDrawer()
  ElMessage({
    message: '操作成功！',
    type: 'success'
  })
}

const onSortChange = data => {
  page.value.sortChange(data)
}

const customerLeveDetailRef = ref()
const onShowCustomerLevel = data => {
  customerLeveDetailRef.value.open(data)
}

const onViewSub = row => {
  subDialog.open({ query: { shopId: row.shopId } })
}

defineOptions({
  name: 'CustomerManagement'
})
</script>
